package com.woniuxy.filter;


import com.woniuxy.dto.UserRelatedDto.UserTableDetails;
import com.woniuxy.exception.PawnJurisdictionException;
import com.woniuxy.mapper.PawnResourceMapper;
import com.woniuxy.service.Impl.LoginErrorHandler;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class AccessFilter extends OncePerRequestFilter {

    private LoginErrorHandler handler;

    private AntPathMatcher apm = new AntPathMatcher();

    private StringRedisTemplate srt;

    private PawnResourceMapper mapper;


    public AccessFilter(LoginErrorHandler handler, StringRedisTemplate srt, PawnResourceMapper mapper) {
        this.handler = handler;
        this.srt = srt;
        this.mapper = mapper;
    }

    public AccessFilter() {

    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取当前的请求地址
        String requestURI = request.getRequestURI();

        Integer userId = null;
        try {
            userId = ((UserTableDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserId();
        } catch (Exception e) {
            filterChain.doFilter(request, response);
            return;
        }

        List<String> range = srt.opsForList().range("pawn:resource:urls:userId:" + userId, 0, -1);

        if (range == null || range.size() <= 0) {

            range = mapper.selectResourceByUserId(userId);
            srt.opsForList().leftPushAll("pawn:resource:urls:userId:" + userId, range);
            srt.expire("pawn:resource:urls:userId:" + userId, 2, TimeUnit.HOURS);
        }

        boolean b = false;
        for (String url : range) {
            if (apm.match(url, requestURI)) {
                b = true;
                break;
            }
        }
        if (b) filterChain.doFilter(request, response);//放行
        else {
            handler.onAuthenticationFailure(request, response, new PawnJurisdictionException("没有权限", 403));//没权限
        }

    }
}
